# -*- coding:utf-8 -*-
import time
import datetime
import os
import json

from exts import *


print("[%s] 评测机开始轮询" % (datetime.datetime.now()))
while True:
    session.commit()
    task = session.query(Task).filter(Task.task_id > 0).first()
    if not task:
        time.sleep(0.1)
        continue
    session.delete(task)
    session.commit()
    session.close()
    print("[%s] 获取评测任务 #%s Problem%s 语言:%s" % (datetime.datetime.now(), task.task_id, task.prob_id, task.language))
    record = session.query(Record).filter(Record.id == task.task_id).first()
    record.status = "Judging"
    session.commit()
    f = open(config.test_temp_dir + "/program." + task.language, "w")
    f.write(task.code)
    f.close()
    os.system("export LANG=en_US.UTF-8 && cd judger && ./Runner " + str(task.prob_id) + " program." + task.language)
    f_res = open("./judger/sandbox/program-result.json", "r")
    res_json = f_res.read()
    f_res.close()
    res_obj = json.loads(res_json)
    if res_obj["Status"] == "CE":
        f_err = open("./judger/sandbox/program_compile_error_info.txt", "r")
        res_obj["compile_info"] = f_err.read()
        f_err.close()
    record.status = res_obj["Status"]
    record.score = int(res_obj["Score"])
    record.result = json.dumps(res_obj)
    session.commit()
    session.close()
    time.sleep(0.1)
